const express = require('express');
const app = express();
app.listen(9000, () => {
  console.log('localhost:9000 服务器启动成功');
});
app.use(express.json());

// 1.终端输入命令npm i express-session

// 2.引入session模块
const session = require('express-session');

// 3.注册session中间件
app.use(session({
  secret: 'express-session', //可为任意字符串
  resave: false, //固定写法
  saveUninitialized: true, //固定写法
}));

// 4.访问Session
app.post('/middleware_session_login', (req, res) => {
  // 验证用户登录信息是否正确
  if (req.body.name !== 'root' || req.body.pwd !== 'root') {
    return res.send('登录失败');
  }
  
  // 存储用户登录信息并修改用户登录状态
  req.session.user = req.body;
  req.session.login = true;
  
  // 登陆成功响应
  res.send('登录成功');
});
app.get('/middleware_session_service', (req, res) => {
  // 验证用户是否登录
  if (!req.session.login) {
    return res.send('未登录');
  }
  
  console.log('身份认证成功');
  console.log(req.session.user); // { name: 'root', pwd: 'root' }
  res.end();
});

// 5.销毁Session
app.get('/middleware_session_destroy', (req, res) => {
  console.log(req.session); // Session {...}
  req.session.destroy();
  console.log(req.session); // undefined
  res.end();
});